<?php
use Illuminate\Database\Eloquent\SoftDeletingTrait;

class OrderDetail extends Eloquent
{
	use SoftDeletingTrait;

	public $timestamps   = true;
	protected $dates     = ['deleted_at'];
	protected $table     = 'order_detail';
	protected $validator = null;

	public function saveData($data, $order)
	{
		$order_detail = new OrderDetail;

		$order_detail->order    = $order;
		$order_detail->product  = (int) $data['product'];
		$order_detail->price    = (double) $data['price'];
		$order_detail->quantity = (int) $data['quantity'];

		$order_detail->save();

		return $order_detail;
	}

	public function deleteOldItems($order)
	{
		$result = OrderDetail::where('order', '=', $order->id)->delete();

		return $result;
	}

	public function getOrderItems($order)
	{
		$result = OrderDetail::leftJoin('product as p', 'p.id', '=', 'order_detail.product')
							->leftJoin('taxonomy as tb', 'tb.id', '=', 'p.brand')
							->select('p.id', 'p.name', 'p.net', 'tb.taxonomy as brand', 'order_detail.price as price', 'order_detail.quantity')
							->where('order_detail.deleted_at', '=', null)
							->where('order_detail.order', '=', $order->id)
							->orderBy('tb.order')
							->get();
		
		return $result;
	}

	public function getOrderItemsToPrint($order)
	{
		$result = DB::table('order_detail as od')
					->leftJoin('product as p', 'p.id', '=', 'od.product')
					->join('taxonomy as tb', 'tb.id', '=', 'p.brand')
					->select('p.id', 'p.name', 'p.net', 'tb.taxonomy as brand', 'od.price as price', 'od.quantity')
					->where('od.deleted_at', '=', NULL)
					->where('od.order', '=', $order->id)
					->orderBy('tb.order')
					->get();
		
		return $result;
	}

	public function order(){
		return $this->belongsTo('order', 'order');
	}
}